package com.nolon.flange.adapter

import android.annotation.SuppressLint
import android.graphics.Paint
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.nolon.flange.R
import com.nolon.flange.databinding.ItemSolutionBinding
import com.nolon.flange.databinding.ItemSolutionHeaderBinding
import com.nolon.flange.model.Part
import com.nolon.flange.model.RawSolution
import com.nolon.flange.tools.percent2
import com.google.android.material.textview.MaterialTextView

class SolutionAdapter(val acc: AppCompatActivity) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    // 表格
    var tableHeaderColor: Int = ContextCompat.getColor(acc, R.color.table_1_header)
    var tableRowOddColor: Int = ContextCompat.getColor(acc, R.color.table_1_row_1)
    var tableRowEvenColor: Int = ContextCompat.getColor(acc, R.color.table_1_row_2)

    // 预览
    var tableHeaderColor2: Int = ContextCompat.getColor(acc, R.color.table_2_header)
    var tableRowOddColor2: Int = ContextCompat.getColor(acc, R.color.table_2_row_1)
    var tableRowEvenColor2: Int = ContextCompat.getColor(acc, R.color.table_2_row_2)

    // 尾部颜色
    val tailColor: Int = ContextCompat.getColor(acc, R.color.grey_500)

    // 控制预览背景色
    var componentColor = tableRowEvenColor2

    // 预览字体色
    var contentColor: Int = ContextCompat.getColor(acc, R.color.black)

    var solutions: List<RawSolution> = arrayListOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    var groupedParts: Map<Int, List<Part>> = mapOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == HEADER_TYPE) {
            val binding = ItemSolutionHeaderBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
            SolutionHeaderViewHolder(binding)
        } else {
            val binding = ItemSolutionBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
            SolutionViewHolder(binding)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (position == 0 && holder is SolutionHeaderViewHolder) {
            holder.binding.layout.setBackgroundColor(tableHeaderColor)
        }
        if (position > 0 && holder is SolutionViewHolder) {
            val solution = solutions[position - 1]
            val raw = solution.rawInfo
            val parts = groupedParts[solution.id]

            with(holder.binding) {
                // 表格
                textNumber.text = "$position#"
                textRawCount.text = "${solution.count}根\n(${raw.actualSpec})"
                textDetails.text = info(parts)
                textUsageRate.text = solution.usageRate.percent2
                textLeft.text = solution.tailLength.toString()

                if (position.rem(2) == 0) {
                    layout.setBackgroundColor(tableRowEvenColor)
                } else {
                    layout.setBackgroundColor(tableRowOddColor)
                }
                // 预览
                // 防止多次添加
                previewContainer.removeAllViews()
                parts?.forEach { part ->
                    val view = createTextView(part.quantity, raw.length)
                    if (part.direction == Part.DIRECTION_LENGTH) {
                        view.paint.flags = Paint.UNDERLINE_TEXT_FLAG
                    }
                    previewContainer.addView(view)
                }
                val tail = createTextView(solution.tailLength, raw.length, true)
                previewContainer.addView(tail)
            }

        }
    }

    override fun getItemCount() = solutions.size + 1

    override fun getItemViewType(position: Int) = if (position == 0) HEADER_TYPE else CONTENT_TYPE

    class SolutionHeaderViewHolder(val binding: ItemSolutionHeaderBinding) :
        RecyclerView.ViewHolder(binding.root)

    class SolutionViewHolder(val binding: ItemSolutionBinding) :
        RecyclerView.ViewHolder(binding.root)

    companion object {
        const val HEADER_TYPE = 0
        const val CONTENT_TYPE = 1
    }

    private fun createTextView(
        partLen: Int,
        totalLen: Int,
        isTail: Boolean = false
    ): MaterialTextView {
        val component = MaterialTextView(acc).apply {
            if (partLen.toFloat() / totalLen > 0.05) {
                text = partLen.toString()
                setTextColor(contentColor)
            }
            ellipsize = TextUtils.TruncateAt.END
            gravity = Gravity.CENTER
            maxLines = 1
            setPadding(0, 20, 0, 20)
            componentColor = when {
                isTail -> {
                    setBackgroundColor(tailColor)
                    tableRowEvenColor2
                }
                else -> {
                    if (componentColor == tableRowOddColor2) {
                        setBackgroundColor(tableRowEvenColor2)
                        tableRowEvenColor2
                    } else {
                        setBackgroundColor(tableRowOddColor2)
                        tableRowOddColor2
                    }
                }
            }
            layoutParams =
                LinearLayoutCompat.LayoutParams(
                    0,
                    100,
//                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    partLen.toFloat() / totalLen
                )
        }
        return component
    }

    private fun info(parts: List<Part>?): String {
        if (parts.isNullOrEmpty()) return ""
        val text = StringBuilder()
        val types = parts.map { it.quantity }.toSet().toList()
        types.forEach { f ->
            text.append(f.toString() + " × " + parts.count { it.quantity == f } + "\n")
        }
        return text.toString().trimEnd('\n')
    }
}